package com.lw.leetcode.arr.b;

import java.util.Arrays;

/**
 * arr
 * 840. 矩阵中的幻方
 *
 * @Author liw
 * @Date 2021/8/8 18:31
 * @Version 1.0
 */
public class NumMagicSquaresInside {

    private int[][] grid;
    private int[] arr = new int[10];

    public int numMagicSquaresInside(int[][] grid) {
        this.grid = grid;
        int a = grid.length - 1;
        int b = grid[0].length - 1;
        int count = 0;


        for (int i = 1; i < a; i++) {
            for (int j = 1; j < b; j++) {
                boolean b1 = find(i, j);
                if (b1) {
                    count++;
                    j++;
                }
            }
        }
        return count;
    }

    private boolean find(int m, int n) {
        if (grid[m][n] != 5) {
            return false;
        }
        Arrays.fill(arr, 0);
        int a = grid[m][n - 1];
        if (a > 9 || a < 0) {
            return false;
        }
        arr[a] = 1;
        int b = grid[m][n + 1];
        if (b > 9 || b < 0) {
            return false;
        }
        if (arr[b] == 1) {
            return false;
        }
        if (a + b != 10) {
            return false;
        }
        int c = grid[m - 1][n - 1];
        if (c > 9 || c < 0) {
            return false;
        }
        if (arr[c] == 1) {
            return false;
        }
        int d = grid[m - 1][n];
        if (d > 9 || d < 0) {
            return false;
        }
        if (arr[d] == 1) {
            return false;
        }
        int e = grid[m - 1][n + 1];
        if (e > 9 || e < 0) {
            return false;
        }
        if (arr[e] == 1) {
            return false;
        }
        if (c + d + e != 15) {
            return false;
        }
        int f = grid[m + 1][n - 1];
        if (f > 9 || f < 0) {
            return false;
        }
        if (arr[f] == 1) {
            return false;
        }
        int g = grid[m + 1][n];
        if (g > 9 || g < 0) {
            return false;
        }
        if (arr[g] == 1) {
            return false;
        }
        int h = grid[m + 1][n + 1];
        if (h > 9 || h < 0) {
            return false;
        }
        if (arr[h] == 1) {
            return false;
        }
        if (f + g + h != 15) {
            return false;
        }
        if (c + a + f != 15) {
            return false;
        }
        if (e + b + h != 15) {
            return false;
        }
        if (d + g != 10) {
            return false;
        }
        if (c + h != 10) {
            return false;
        }
        return e + f == 10;
    }
}
